package com.tyqx.hashchainutil.common;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
// import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tyqx.hashchainutil.org.app.config.Config;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RunShell {


    public static void invokeShell(String[] path) {
        Map<String, String> map = new HashMap<>();
        try {
            Runtime runtime = Runtime.getRuntime();
            Process pro = runtime.exec(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            BufferedReader brErr = new BufferedReader(new InputStreamReader(pro.getErrorStream()));
            StringBuffer brSb = new StringBuffer();
            StringBuffer brErrSb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("br={" + line + "}");
                brSb.append(line);
            }
            while ((line = brErr.readLine()) != null) {
                System.out.println("brErr={" + line + "}");
                brErrSb.append(line);
            }

            if (null != br) {
                br.close();
            }
            if (null != brErr) {
                brErr.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 调用shell脚本
     *
     * @param path
     */

    public static Map<String, String> invokeShell(String[] path, String methodType) {
        Map<String, String> map = new HashMap<>();
        Map<String, String> lineMap = new HashMap<>();
        try {
            Runtime runtime = Runtime.getRuntime();
            Process pro = runtime.exec(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            BufferedReader brErr = new BufferedReader(new InputStreamReader(pro.getErrorStream()));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("br={" + line + "}");
                if (methodType.equals("getBlockData")) {
                    if (EmptyUtils1.isNotEmpty(line)) {
                        lineMap.put("blockDataStr", line);
                    }
                } else if (methodType.equals("getBalance")) {
                    if (EmptyUtils1.isNotEmpty(line)) {
                        lineMap.put("getBalance", line);
                    }
                } else if (methodType.equals("setBalance")) {
                    if (EmptyUtils1.isNotEmpty(line)) {
                        lineMap.put("setBalance", line);
                    }
                } else if (methodType.equals("charge")) {
                    if (EmptyUtils1.isNotEmpty(line)) {
                        lineMap.put("charge", line);
                    }
                }else if (methodType.equals("insertHashItem")) {
                    JsonObject insertHashItemJson = new JsonParser().parse(line).getAsJsonObject();

                    String txid=insertHashItemJson.get("TXID").getAsString();
                    String blockNum=insertHashItemJson.get("BLOCK_NUM").getAsString();


                    if(EmptyUtils1.isNotEmpty(txid)){
                        lineMap.put("txid", txid);
                    }
                    if(EmptyUtils1.isNotEmpty(blockNum)){
                        lineMap.put("blockNum", blockNum);
                    }
                }
            }

            while ((line = brErr.readLine()) != null) {
                System.out.println("brErr={" + line + "}");
            }
            if (null != br) {
                br.close();
            }
            if (null != brErr) {
                brErr.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lineMap;
    }


    /**
     * 执行远程服务器上的shell脚本
     *
     * @param ip   服务器IP地址
     * @param port 端口号
     * @param name 登录用户名
     * @param pwd  密码
     * @param cmds shell命令
     */
    public static void RemoteInvokeShell(String ip, int port, String name, String pwd, String[] cmds) {
        //log.info("ip:"+ip+" port:"+port+" name:"+name+" password:"+pwd);
        System.out.println("ip:" + ip + " port:" + port + " name:" + name + " password:" + pwd);
        StringBuffer cmd = new StringBuffer();
        for (String s : cmds) {
            if (s.contains("|") || s.contains(" ")) { //如果包含特殊符号
                s = "\"" + s + "\"";
            }
            cmd.append(s).append(" ");
        }
        String cmdd = cmd.toString();
        //cmdd=cmdd.substring(0,cmdd.length()-1);
        //log.info("invoke shell:{}",cmdd);
        System.out.println("invoke shell:{" + cmdd + "}");
        Connection conn = null;
        try {
            conn = new Connection(ip, port);
            conn.connect();
            if (conn.authenticateWithPassword(name, pwd)) {
                // Open a new {@link Session} on this connection
                Session session = conn.openSession();
                // Execute a command on the remote machine.
                session.execCommand(cmdd);

                BufferedReader br = new BufferedReader(new InputStreamReader(session.getStdout()));
                BufferedReader brErr = new BufferedReader(new InputStreamReader(session.getStderr()));

                String line;
                while ((line = br.readLine()) != null) {
                    //log.info("br={}", line);
                    System.out.println("br={" + line + "}");
                }
                while ((line = brErr.readLine()) != null) {
                    //log.info("brErr={}", line);
                    System.out.println("brErr={" + line + "}");
                }
                if (null != br) {
                    br.close();
                }
                if (null != brErr) {
                    brErr.close();
                }
                session.waitForCondition(ChannelCondition.EXIT_STATUS, 0);
                int ret = session.getExitStatus();
                //log.info("getExitStatus:"+ ret);
                System.out.println("getExitStatus:" + ret);
            } else {
                //log.info("登录远程机器失败" + ip);
                System.out.println("登录远程机器失败" + ip);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.close();
            }
        }
    }

    /**
     * 上传文件到远程服务器
     */
    public static void remoteUploadFile(String ip, int port, String name, String pwd, String filePath, String fileName, File file) {
        //log.info("remoteUploadFile.... ");
        System.out.println("remoteUploadFile.... ");
        Connection connection = new Connection(ip, port);
        try {
            connection.connect();
            boolean isAuthenticated = connection.authenticateWithPassword(name, pwd);
            if (!isAuthenticated) {
                //log.info("登录远程机器失败" + ip);
                System.out.println("登录远程机器失败" + ip);
                return;
            }
            SCPClient scpClient = new SCPClient(connection);
            scpClient.put(filePath + fileName, filePath);
            if (null != connection) {
                connection.close();
            }
            //log.info("upload ok");
            System.out.println("upload ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        //调用脚本
       /* String path[]={"sh","/root/ZhangZhemin/lhb.sh",//shell脚本的存放路径
                "--shp","aaa|bbb|ccc",//"--shp"代表的是shell脚本里面的参数名  aaa|bbb|ccc 代表参数值
                "--dbf","dddd",
                "--location-info","",
                "--check-line-geo","T_CHECKLINE_SUB_INFO",
                "--project-id","",
                "--check-line-station","T_CHECKLINE_LACCI",
                "--check-line-info-name","T_CHECKLINE_INFO",
                "--import-info-name","T_IMPORT_TASK",
                "--abs-distance","",
                "--buffer-distance","",
                "--max-length","",
                "--max-related-distance","",
                "--import-task-id","",
                "--check-line-id","",
                "--db-info",""
        };*/
//        String path[]={"sh","/home/zhangzhemin/lhb.sh"};
//        String path[]={"sh","/Users/zhangzhemin/dynamicChain/javaCall/javaCall.sh"};
//        invokeShell(path);//本机调用
    }
}
